//
//  BMSNetworkSessionManager.m
//  BMSSDK
//
//  Created by YeJary on 2025/4/27.
//

#import "BMSNetworkSessionManager.h"
#import <AFNetworking/AFNetworking.h>
#import "BMSNetworkEnvironment.h"
//#import "WDAESUtil.h"
//#import "WDTools.h"

@interface BMSNetworkSessionManager ()

@property (nonatomic, strong) AFHTTPSessionManager *sessionManager;
@property (nonatomic, copy) NSString *baseURL;

@end

@implementation BMSNetworkSessionManager

+ (instancetype)sharedManager {
    static BMSNetworkSessionManager *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[BMSNetworkSessionManager alloc] init];
        instance->_environment = [[BMSNetworkEnvironment alloc] init];
        [instance->_environment switchEnvironment:BMSNetworkEnvironmentTypeProduction]; // 默认环境
        [instance setupSessionManager];
    });
    return instance;
}

- (void)switchEnvironment:(BMSNetworkEnvironmentType)type {
    [self.environment switchEnvironment:type];
}

- (void)setupSessionManager {

    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    config.timeoutIntervalForRequest = 15;

    self.sessionManager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:config];
    self.sessionManager.responseSerializer = [AFJSONResponseSerializer serializer];
    self.sessionManager.requestSerializer = [AFJSONRequestSerializer serializer];
    self.sessionManager.responseSerializer.acceptableContentTypes =
        [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", nil];

    [self.sessionManager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
    // 示例 Token 注入（可根据实际需求替换）
    NSString *token = @"user-token";
    if (token.length > 0) {
        [self.sessionManager.requestSerializer setValue:token forHTTPHeaderField:@"Authorization"];
    }
}

#pragma mark - 通用请求方法
- (void)requestWithMethod:(NSString *)method
                      URL:(NSString *)url
               parameters:(NSDictionary *)parameters
                  success:(BMSNetworkSuccessBlock)success
                  failure:(BMSNetworkFailureBlock)failure {
    NSString *fullURL = url;
    if (![url containsString:@"https"]) {
        NSURL *base = [NSURL URLWithString:[self.environment currentBaseURL]];
        NSURL *full = [NSURL URLWithString:url relativeToURL:base];
        fullURL = [NSString stringWithFormat:@"%@",full.absoluteURL];
        NSLog(@"[WDNetwork] 请求地址: %@\n参数: %@", fullURL, parameters);
    }

    if ([[method uppercaseString] isEqualToString:@"GET"]) {
        [self.sessionManager GET:fullURL parameters:parameters headers:nil progress:nil
                          success:^(NSURLSessionDataTask *task, id responseObject) {
            if (success) success(responseObject);
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            if (failure) failure(error);
        }];

    } else if ([[method uppercaseString] isEqualToString:@"POST"]) {
//        [self.sessionManager POST:fullURL parameters:finalParams headers:nil progress:nil
//                           success:^(NSURLSessionDataTask *task, id responseObject) {
//            if (success) success(responseObject);
//        } failure:^(NSURLSessionDataTask *task, NSError *error) {
//            if (failure) failure(error);
//        }];
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil];
        NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        
        // 3. 构造原始 POST 请求
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:fullURL]];
        request.HTTPMethod = @"POST";
        request.timeoutInterval = 15;
        [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

        NSMutableArray *formComponents = [NSMutableArray array];
        BOOL shouldEncode = ![url containsString:@"/common/rna/check"]; // ❗️实名接口不编码

        [parameters enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
            NSString *encodedKey = shouldEncode ? [BMSNetworkSessionManager urlEncode:[NSString stringWithFormat:@"%@", key]] : key;
            NSString *encodedValue = shouldEncode ? [BMSNetworkSessionManager urlEncode:[NSString stringWithFormat:@"%@", obj]] : obj;
            [formComponents addObject:[NSString stringWithFormat:@"%@=%@", encodedKey, encodedValue]];
        }];
        NSString *formBody = [formComponents componentsJoinedByString:@"&"];
        request.HTTPBody = [formBody dataUsingEncoding:NSUTF8StringEncoding];
        
        NSURLSession *session = [NSURLSession sharedSession];
        NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                                completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
            if ([url containsString:@"/common/rna/check"]) {
                NSHTTPURLResponse *httpResponse = response;
                NSString *dateString = nil;
                
                for (NSString *key in httpResponse.allHeaderFields) {
                    if ([key.lowercaseString isEqualToString:@"date"]) {
                        dateString = httpResponse.allHeaderFields[key];
                        break;
                    }
                }
                
                if (dateString) {
                    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                    formatter.dateFormat = @"EEE',' dd MMM yyyy HH':'mm':'ss z";
                    formatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
                    formatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"]; // 服务端时间为 GMT
                    
                    NSDate *gmtDate = [formatter dateFromString:dateString];
                    if (gmtDate) {
                        // 转换为中国时区
                        NSDateFormatter *chinaFormatter = [[NSDateFormatter alloc] init];
                        chinaFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
                        chinaFormatter.timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
                        
                        NSString *chinaTimeString = [chinaFormatter stringFromDate:gmtDate];
                        NSLog(@"[ServerTime] 🇨🇳 中国时间: %@", chinaTimeString);
                        [[NSUserDefaults standardUserDefaults]setObject:chinaTimeString forKey:@"BMS_ServerTimeOffset"];
                        
                        // 如果你需要 NSDate 对象，可直接使用 gmtDate，它在内存中表示的是一个时间点，可自由转换时区。
                    } else {
                        NSLog(@"[ServerTime] ❌ GMT 日期字符串解析失败: %@", dateString);
                    }
                } else {
                    NSLog(@"[ServerTime] ⚠️ 响应头中未找到 Date 字段");
                }
            }
            if (error) {
                if (failure) dispatch_async(dispatch_get_main_queue(), ^{ failure(error); });
            } else {
                id json = nil;
                if (data) {
                    json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
                }
                if (success) dispatch_async(dispatch_get_main_queue(), ^{ success(json); });
            }
        }];
        [task resume];
        return;

    } else {
        NSLog(@"⚠️ 不支持的请求方法: %@", method);
        if (failure) {
            NSError *error = [NSError errorWithDomain:@"WDNetworkErrorDomain" code:-10000 userInfo:@{NSLocalizedDescriptionKey: @"不支持的请求方法"}];
            failure(error);
        }
    }
}

#pragma mark - 快捷封装方法
- (void)getWithURL:(NSString *)url
        parameters:(NSDictionary *)parameters
           success:(BMSNetworkSuccessBlock)success
           failure:(BMSNetworkFailureBlock)failure {
    [self requestWithMethod:@"GET" URL:url parameters:parameters success:success failure:failure];
}

- (void)postWithURL:(NSString *)url
         parameters:(NSDictionary *)parameters
            success:(BMSNetworkSuccessBlock)success
            failure:(BMSNetworkFailureBlock)failure {
    [self requestWithMethod:@"POST" URL:url parameters:parameters success:success failure:failure];
}

#pragma mark - JSON 工具
- (NSString *)jsonStringFromDict:(NSDictionary *)dict {
    if (!dict) return @"";
    NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil];
    return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}

+ (NSString *)urlEncode:(NSString *)string {
    NSCharacterSet *allowed = [NSCharacterSet URLQueryAllowedCharacterSet];
    return [string stringByAddingPercentEncodingWithAllowedCharacters:allowed];
}

@end

